﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using AutoMapper;
using KSUNO_EMS.Models;
using Encryption;

namespace KSUNO_EMS
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Login", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            CreateMaps();
        }
        private static string ToTime(int timeInMinutes)
        {
            var dateTime = DateTime.Today.Add(TimeSpan.FromMinutes(timeInMinutes));

            return String.Format("{0:hh\\:mm tt}", dateTime);
        }
        private static void CreateMaps()
        {
            Mapper.CreateMap<Employee, EmployeeDTO>()
                .ForMember(m => m.Password, opt => opt.MapFrom(src => ""))
                .ForMember(m => m.AvailableTimes,
                           opt =>
                           opt.MapFrom(
                               src =>
                               src.Availability.ToList().GroupBy(g => g.Day).ToDictionary(g => g.Key,
                                                                                          g => String.Join(",", g.Select(a => String.Format("{0}-{1}", ToTime(a.From), ToTime(a.To)))))));
            Mapper.CreateMap<EmployeeDTO, Employee>()
                .ForMember(m => m.Password, opt => opt.MapFrom(src => Hash.GetHash(src.Password, Hash.HashType.SHA256)));

            Mapper.CreateMap<Test, TestDTO>();
            Mapper.CreateMap<TestDTO, Test>();
            Mapper.CreateMap<TestQuestion, TestQuestionDTO>()
                .ForMember(m=>m.CorrectAnswerId, opt=>opt.MapFrom(src=>src.CorrectAnswer.Id));
            Mapper.CreateMap<TestQuestionDTO, TestQuestion>();
            Mapper.CreateMap<TestQuestionAnswer, TestQuestionAnswerDTO>();
            Mapper.CreateMap<TestQuestionAnswerDTO, TestQuestionAnswer>();
            Mapper.CreateMap<JobApplicant, JobApplicantDTO>();
            Mapper.CreateMap<JobApplicantDTO, JobApplicant>().ForMember(m => m.Id, opt => opt.Ignore());

            Mapper.CreateMap<Document, DocumentDTO>();
            Mapper.CreateMap<Employee, EmployeeProfileDTO>()
                .ForMember(m => m.AvailableTimes,
                           opt =>
                           opt.MapFrom(
                               src =>
                               src.Availability.ToList().GroupBy(g => g.Day).ToDictionary(g => g.Key,
                                                                                          g => String.Join(",", g.Select(a => String.Format("{0}-{1}", ToTime(a.From), ToTime(a.To)))))));
            Mapper.CreateMap<EmployeeProfileDTO, Employee>()
                .ForMember(m => m.Id, opt => opt.Ignore());

        }

        public static EmployeeDTO GetCurrentUserInfo()
        {
            var session = HttpContext.Current.Session;
            var user = HttpContext.Current.User;
            // Retrieve the user's info from the Session
            var userInfo = session[user.Identity.Name] as Models.EmployeeDTO;
            // If their session has expired, retrieve the info from the database
            if (userInfo == null)
                using (var db = new EmsDb())
                {
                    var employee = db.Employees.SingleOrDefault(e => e.Username == user.Identity.Name);
                    if (employee != null)
                        userInfo = Mapper.Map<Employee, EmployeeDTO>(employee);
                }
            //// If we can't get the info from the database, sign the user out
            //if (userInfo == null)
            //{
            //    FormsAuthentication.SignOut();
            //    FormsAuthentication.RedirectToLoginPage();
            //}

            return userInfo;
        }

    }
}